<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/8/11
 * Time: 11:54
 */
namespace App\Services;

use App\Repositories\UserLevelRelationsRepository;
use App\Repositories\UserRepository;
use App\Services\JMessage\JMessageService;
use Laravel\Passport\Token;
use Illuminate\Support\Facades\Hash;

class UserService extends CommonService
{
    protected $userRepository;
    protected $userLevelRelationsRepository;
    protected $messageService;

    public function __construct(UserRepository $userRepository, UserLevelRelationsRepository $userLevelRelationsRepository,
                                MessageService $messageService)
    {
        $this->userRepository = $userRepository;
        $this->userLevelRelationsRepository = $userLevelRelationsRepository;
        $this->messageService = $messageService;
    }

    public function create(array $data)
    {
        $this->userRepository->create($data);
    }

    public function insertGetId(array $data)
    {
        $this->userRepository->insertGetId($data);
    }

    /**
     * 注册用户
     * @param $mobile
     * @param $password
     * @param $code
     * @return \Illuminate\Http\JsonResponse
     */
    public function registerUser($mobile, $password, $code, $invitedCode)
    {
        $isCheck = $this->checkCode($mobile, $code, 'register');
        if (!$isCheck) {
            return $this->responseJson(10110);//短信验证码不正确
        }
        $isExists = $this->userRepository->byMobile($mobile);
        if (!empty($isExists)) {
            return $this->responseJson(10101);//手机号码已被占用
        }
        $data = [
            'mobile' => $mobile,
            'password' => bcrypt($password),
            'reg_time' => time(),
        ];
        //用户等级关系 0000 是对应user_id为0的用户
        $invitedCode = strtoupper($invitedCode);
        $invitedUserId = invitedDeCode($invitedCode);//解开邀请人的user_id
        if (0 < $invitedUserId) {
            //获取邀请人
            $invitedUser = $this->userRepository->byId($invitedUserId);
            if (empty($invitedUser)) {
                return $this->responseJson(10111);//邀请码不存在
            }
            //根据user_id与当前邀请人的等级，查找关系表，邀请人对应的关系id
            $getInvitedUserRelationsId = $this->userLevelRelationsRepository->first($invitedUser->user_id);
            if (!empty($getInvitedUserRelationsId)) {
                $userId = $this->userRepository->insertGetId($data);
                $levelData = [
                    'user_id' => $userId,
                    'level_id' => 4,
                    'pid' => $getInvitedUserRelationsId->id,
                    'create_time' => time(),
                ];
                //发送邀请成功消息提醒
                $this->messageService->messageTemplate(6, $invitedCode, '', '',
                    0, '', $mobile, 0, '', '');
            } else {
                return $this->responseJson(400);//邀请人关系不存在
            }
        } else {
            $userId = $this->userRepository->insertGetId($data);
            //pid=0属于使用平台邀请码
            $levelData = [
                'user_id' => $userId,
                'level_id' => 4,
                'pid' => 0,
                'create_time' => time(),
            ];
        }
        $this->userLevelRelationsRepository->create($levelData);
        if (0 < $userId) {
            $invitedEnCode = invitedEnCode($userId);
            $user = $this->userRepository->byId($userId);
            $user->update(['invited_code' => $invitedEnCode]);
            //注册极光im用户
            $jMessageService = new JMessageService();
            $jMessageService->register($invitedEnCode, $invitedEnCode);
        }
        return $this->responseJson(0, [], false, 'success', '注册成功');
    }

    /**
     * 更新密码
     * @param $mobile
     * @param $password
     * @param $code
     * @return \Illuminate\Http\JsonResponse
     */
    public function updatePassword($mobile, $password, $code)
    {
        
        $isCheck = $this->checkCode($mobile, $code, 'forget_password');
        if (!$isCheck) {
            return $this->responseJson(10110);//短信验证码不正确
        }
        $isExists = $this->userRepository->byMobile($mobile);
        if (empty($isExists)) {
            return $this->responseJson(10102);//手机号码不存在
        }
        $data = [
            'password' => bcrypt($password),
        ];
        $isExists->update($data);
        $this->deleteTokens($isExists->user_id);
        return $this->responseJson(0);
    }

    /**
     * 忘记支付密码
     * @param $mobile
     * @param $password
     * @param $code
     * @return \Illuminate\Http\JsonResponse
     */
    public function forgetPayPassword($mobile, $password, $code, $userMobile)
    {
        //是否该用户手机
        if ($mobile != $userMobile) {
            return $this->responseJson(10113);//手机号码未绑定该账号
        }
        $isCheck = $this->checkCode($mobile, $code, 'forget_pay_password');
        if (!$isCheck) {
            return $this->responseJson(10110);//短信验证码不正确
        }
        $isExists = $this->userRepository->byMobile($mobile);
        if (empty($isExists)) {
            return $this->responseJson(10102);//手机号码不存在
        }
        $data = [
            'paypwd' => bcrypt($password),
        ];
        $isExists->update($data);
        return $this->responseJson(0);
    }

    /**
     * 查找手机号码是否已存在
     * @param $mobile
     * @return \Illuminate\Http\JsonResponse
     */
    public function findMobileIsExists($mobile)
    {
        $isExists = $this->userRepository->byMobile($mobile);
        if (!empty($isExists)) {
            return $this->responseJson(10101);//手机号码已被占用
        } else {
            return $this->responseJson(0);
        }
    }

    /**
     * 修改登录密码
     * @param $id
     * @param $oldPassword
     * @param $newPassword
     * @return \Illuminate\Http\JsonResponse
     */
    public function modifyLoginPassword($id, $oldPassword, $newPassword)
    {
        $user = $this->userRepository->byId($id);
        $isCheck = $this->checkOldPassword($oldPassword, $user->password);
        if (!$isCheck) {
            return $this->responseJson(10103);//原登录密码不正确
        }
        $data = [
            'password' => bcrypt($newPassword),
        ];
        $user->update($data);
        $this->deleteTokens($id);
        return $this->responseJson(0);
    }

    /**
     * 修改支付密码
     * @param $id
     * @param $password
     * @param string $mobile
     * @return \Illuminate\Http\JsonResponse
     */
    public function modifyPayPassword($id, $oldPassword, $newPassword, $mobile)
    {
        $user = $this->userRepository->byId($id);
        //是否该用户手机
        if ($mobile != $user->mobile) {
            return $this->responseJson(10113);//手机号码未绑定该账号
        }
        if (!empty($user->paypwd)) {
            $isCheck = $this->checkOldPassword($oldPassword, $user->paypwd);
            if (!$isCheck) {
                return $this->responseJson(10104);//原支付密码不正确
            }
        }
        $data = [
            'paypwd' => bcrypt($newPassword),
        ];
        $user->update($data);
        return $this->responseJson(0);
    }

    /**
     * 检查旧密码是否正确
     * @param $inputPassword
     * @param $hashedPassword
     * @return bool
     */
    protected function checkOldPassword($inputPassword, $hashedPassword)
    {
        if (Hash::check($inputPassword, $hashedPassword)) {
            return true;
        }
        return false;
    }

    /**
     * 修改用户头像
     * @param $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function modifyHeadImage($request, $id)
    {
        $user = $this->userRepository->byId($id);
        //上传新图片
        $uploadFilePath = $this->upload('alioss', 'avatr', $request->pic);
        if (is_object($uploadFilePath)) return $uploadFilePath;
        //删除旧图片
        if (!empty($user->head_pic)) {
            $uploadOSSorStorage = new UploadOSSorStorage();
            $uploadOSSorStorage->deleteOSSorStorageLocal($user->head_pic, "alioss");
        }
        //更新用户头像
        $user->update(['head_pic' => $uploadFilePath]);
        return $this->responseJson(0, ['head_pic' => getOssImageUrl($uploadFilePath)]);
    }

    /**
     * 修改密码或忘记密码都 清理access_token
     * @param $userId
     * @param $clientId
     * @return mixed
     */
    protected function deleteTokens($userId)
    {
        return Token::where('user_id', $userId)->delete();
    }

}